Skip to content

Conversation

@bzEq
Copy link
Collaborator

@bzEq bzEq commented Dec 30, 2024

For following program compiled with clang++ tls.cc -femulated-tls -O3 -rtlib=compiler-rt -unwindlib=libunwind on X86_64, there is chance the first allocated object is different from other allocation.

#include <atomic>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

thread_local int id = 0;
std::mutex print_mutex;

int main() {
  // std::cout << "thread " << 0 << ": " << &id << std::endl;
  std::vector<std::thread> group;
  for (int i = 1; i < 8; ++i) {
    group.emplace_back([i] {
      std::unique_lock<std::mutex> _(print_mutex);
      std::cout << "thread " << i << ": " << &id << std::endl;
    });
  }
  for (auto &t : group) t.join();
  return 0;
}

Output:
thread 1: 0x7f57040010a8
thread 2: 0x7f56fc000c98
thread 3: 0x7f56fc000c98
thread 5: 0x7f56fc000c98
thread 4: 0x7f56fc000c98
thread 6: 0x7f56fc000c98
thread 7: 0x7f56fc000c98

Also I have a question, is this implementation broken since it's returning the same address for the same thread_local variable in different threads.

For following program compiled with `-femulated-tls`, there is chance
the first allocated object is different from other allocation.
```

thread_local int id = 0;
std::mutex print_mutex;

int main() {
  // std::cout << "thread " << 0 << ": " << &id << std::endl;
  std::vector<std::thread> group;
  for (int i = 1; i < 8; ++i) {
    group.emplace_back([i] {
      std::unique_lock<std::mutex> _(print_mutex);
      std::cout << "thread " << i << ": " << &id << std::endl;
    });
  }
  for (auto &t : group) t.join();
  return 0;
}

Output:
thread 1: 0x7f57040010a8
thread 2: 0x7f56fc000c98
thread 3: 0x7f56fc000c98
thread 5: 0x7f56fc000c98
thread 4: 0x7f56fc000c98
thread 6: 0x7f56fc000c98
thread 7: 0x7f56fc000c98
```
@bzEq bzEq closed this Dec 30, 2024
@bzEq bzEq reopened this Dec 30, 2024
@bzEq bzEq marked this pull request as draft December 30, 2024 09:30
@bzEq bzEq closed this Dec 30, 2024
@bzEq bzEq deleted the get-address-race branch February 16, 2025 06:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants